package com.mydroidchat.controllers;

import com.mydroidchat.data.net.LoginApiRequest;
import com.mydroidchat.data.net.LoginApiResponse;
import com.mydroidchat.views.LoginPanelView;
import com.mydroidchat.views.SigningInDialogView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginController extends Controller {
    private static LoginController instance;
    private final LoginPanelView loginView;

    private LoginController() {
        loginView = new LoginPanelView();
        loginView.getExitButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        loginView.getSignInButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                signIn();
            }
        });
    }

    private void signIn() {
        final SigningInDialogView signingInDialogView = new SigningInDialogView(ChatApplicationController.getInstance().getWindowView());
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                signingInDialogView.setVisible(true);
            }
        });
        LoginApiRequest request = new LoginApiRequest(loginView.getLoginTextField().getText(), new String(loginView.getPasswordField().getPassword()));
        LoginApiResponse response = request.execute();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                signingInDialogView.setVisible(false);
            }
        });
        if (!response.isSuccess()) {
            JOptionPane.showMessageDialog(loginView, "Please enter your valid login and password!", "Login failed :(", JOptionPane.ERROR_MESSAGE);
        } else {
            System.err.println("good");
            ChatApplicationController.getInstance().setActiveController(new ChatPanelController());
        }
    }
    
    public static LoginController getInstance() {
        if (instance == null) {
            instance = new LoginController();
        }
        return instance;
    }
    
    @Override
    public Container getView() {
        return loginView;
    }

    @Override
    public void refresh() {

    }
}
